import base64

from playwright.sync_api import Playwright, sync_playwright, expect


def run(playwright: Playwright) -> None:

    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://10.0.24.101/login.html")
    page.locator("#userName").fill("17778024244")
    page.locator("#passWord").fill("Aa123456@")
    page.get_by_role("button", name="登录").click()
    print("===登录成功===")
    # expect(page.locator("div#toolbar_header_function").locator("span.application-icon")).to_have_class("f-icon")
    page.get_by_title("我的应用").click()  # page.locator("div#toolbar_header_function").click()
    page.get_by_text("财务共享").click()  # page.locator("span.menu-item--text:has-text('财务共享')").click()
    page.get_by_text("网上报账服务").click()
    page.get_by_text("我要报账").first.click()  # page.locator("div.application-wrapper--list-item-text").filter(has_text="我要报账").click()
    print("===打开我要报账===")

    # 等待表格打开
    expect(page.frame_locator("iframe >> nth=1").locator("[id=\"grid_main_filter_TREEID_FSDJTREE_NAME\\$LANGUAGE\\$\"]")).to_be_enabled()
    # 搜索过滤”合同报销单“
    page.frame_locator("iframe >> nth=1").locator("[id=\"grid_main_filter_TREEID_FSDJTREE_NAME\\$LANGUAGE\\$\"]").click()
    page.frame_locator("iframe >> nth=1").locator("[id=\"grid_main_filter_TREEID_FSDJTREE_NAME\\$LANGUAGE\\$\"]").fill("合同报销单")


    # page1.wait_for_timeout(3000)
    # 自动等待元素就位,之后再操作可保证不因元素不存在而出错
    expect(page.frame_locator("iframe >> nth=1").locator("div.lee-grid-main").locator("table.lee-grid-body-table tr > td").last).to_be_enabled()  # div.lee-grid-body-main div.lee-grid-body-inner
    print("tr元素个数：", page.frame_locator("iframe >> nth=1").locator("div.lee-grid-main table.lee-grid-body-table>tbody>tr.lee-grid-row").count())
    l_count_tr = 0
    for i_tr in page.frame_locator("iframe >> nth=1").locator("div.lee-grid-main table.lee-grid-body-table>tbody>tr.lee-grid-row").all():
        if i_tr.locator("th").count() > 0:
            continue
        l_count_tr += 1
        print(i_tr.inner_html())
        if i_tr.locator("[id=\"grid_main|2|r100{}|FSBZDJ_DJBH\"]".format(l_count_tr)).locator("div.lee-grid-row-cell-inner>a.FSBZDJ_DJBH").count() ==0:
            continue
        code = i_tr.locator("[id=\"grid_main|2|r100{}|FSBZDJ_DJBH\"]".format(l_count_tr)).locator("div.lee-grid-row-cell-inner>a.FSBZDJ_DJBH").inner_html()
        if code.isspace():
            continue
        print("code:", code)
    # page1.wait_for_timeout(3000)
    # page1.screenshot(path="screenshot.png")
    print("操作结束")
    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)
